package com.example.utils;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class CacheUtils {

    @Resource
    StringRedisTemplate stringRedisTemplate;

    public <T> T takeFromCache(String key, Class<T> dataType) {
        String s = stringRedisTemplate.opsForValue().get(key);
        if(s == null) return null;
        return JSONObject.parseObject(s).to(dataType);
    }

    public <T> List<T> takeListFromCache(String key, Class<T> itemType) {
        String s = stringRedisTemplate.opsForValue().get(key);
        if(s == null) return null;
        return JSONArray.parseArray(s).toList(itemType);
    }

    public <T> void savaToCache(String key, T data, long expire) {
        //将传入的数据对象 data 转换为 JSON 字符串并存入缓存
        stringRedisTemplate.opsForValue().set(key, JSONObject.from(data).toJSONString(), expire, TimeUnit.MINUTES);
    }

    public <T> void saveListToCache(String key, List<T> list, long expire) {
        stringRedisTemplate.opsForValue().set(key, JSONArray.from(list).toJSONString(), expire, TimeUnit.MINUTES);
    }

    public void deleteCachePattern(String key) {
        Set<String> keys = stringRedisTemplate.keys(key);
        keys.forEach(k -> {
            stringRedisTemplate.delete(k);
        });
    }


    public void deleteCache(String key) {
        Boolean delete = stringRedisTemplate.delete(key);
        if (delete) {
            log.info("删除缓存{}成功", key);
        } else {
            log.info("删除缓存{}失败", key);
        }
    }
}
